<script setup lang='ts'>
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { Search, Minus, Plus } from "@element-plus/icons-vue";

import { ElMessage } from "element-plus";
import { useEnumStore } from "@/store/enumeration"
import { voucherSaveOrUpdateSavePost } from "@/api/equity"
import useInstance from "@/hooks/useInstance";
import BlackSelect from "@/components/customSon/blackSelect.vue";

import { useComListData } from "@/store/list"
const { getVirtualType, listCollect } = useComListData()
defineOptions({
    name: "addEquAd",
});
const props = defineProps({
    supplierCodeList: {
        type: Array,
        default: () => []
    }
})
const {  expiryPeriodType, isShow, schemeConfigletailsType, virtualType } = useEnumStore()
const emit = defineEmits(["refresh",'searchEdit']);
const { global } = useInstance();
const dialogBasic = ref({
    title: "新建权益立减金",
    visible: false,
    width: 760,
    height: 550,
    showFooter: true,
    marginTop: "10vh",
});

const ruleFormRef = ref<FormInstance>();

const channelForm = reactive<any>({
    supplierCode: null, //  供应商编码
    equityVoucherType: null, //  权益券类型
    equityVoucherName: null, //  权益券名称
    supplierEquityVoucherCode: null, //  供应商权益编码
    receiveType: null, //  领取类型
    receiveValue: null, //  领取值
    reductionVoucherAmount: null, //  立减金额度
    expiryPeriod: null, //  过期期限
    expiryPeriodType: 2, //  过期期限类型
    enabled: null, //  是否启用
    extInfo: [
        {
            key: null,
            value: null,
        },
    ],
});
const changeClick = async (item: number, flag?: boolean) => {
    if (!flag) {
        channelForm.receiveValue = null
    }
    console.log(item);
    if (item == 1) {
        getVirtualType('BANK')
    } else {
        getVirtualType('VIRTUAL_MEMBER')
    }
}
const rules = reactive<FormRules>({

    expiryPeriod: [
        {
            required: true,
            trigger: "blur",
            message: "请输入过期期限",
        },
    ],
    reductionVoucherAmount: [
        {
            required: true,
            trigger: "blur",
            message: "请输入立减金额度",
        },
    ],
/*     receiveValue: [
        {
            required: true,
            trigger: "blur",
            message: "请输入领取值",
        },
    ],
    receiveType: [
        {
            required: true,
            trigger: "blur",
            message: "请选择领取类型",
        },
    ], */
    supplierEquityVoucherCode: [
        {
            required: true,
            trigger: "blur",
            message: "请输入供应商权益编码",
        },
    ],
    equityVoucherName: [
        {
            required: true,
            trigger: "blur",
            message: "请输入权益券名称",
        },
    ],
    equityVoucherType: [
        {
            required: true,
            trigger: "blur",
            message: "请选择权益券类型",
        },
    ],
    supplierCode: [
        {
            required: true,
            trigger: "blur",
            message: "请选择供应商编码",
        },
    ],
    enabled: [
        {
            required: true,
            trigger: "blur",
            message: "请选择是否启用",
        },
    ],


});
//显示弹框
const show = (type: string, row?: any) => {
    dialogBasic.value.visible = true;
    console.log(type, row);

    if (type == "add") {
        dialogBasic.value.title = "新建权益券";
        dialogBasic.value.height = 500;
        global.$resetForm(ruleFormRef.value, channelForm);
        channelForm.expiryPeriodType = 2
        channelForm.extInfo = [
            {
                key: null,
                value: null
            }
        ]
        resetForm();
    } else {
        dialogBasic.value.height = 550;

        global.$resetForm(ruleFormRef.value, channelForm);
        dialogBasic.value.title = "编辑权益券";
        // global.$objCopy(channelForm, row);
        Object.assign(channelForm, row)
        changeClick(row.receiveType, true)
        channelForm.expiryPeriodType = 2
        const arr = JSON.parse(row.extInfo)

        if (arr && Object.keys(arr).length > 0) {
            channelForm.extInfo = []

            Object.keys(arr).forEach(item => {
                console.log(typeof arr[item]);

                channelForm.extInfo.push({
                    key: item,
                    value: arr[item]
                })
            })
        } else {
            channelForm.extInfo = [
                {
                    key: null,
                    value: null
                }
            ]
        }
    }
};
const onClose = () => {
    dialogBasic.value.visible = false;
    channelForm.extInfo = [
        {
            key: null,
            value: null
        }
    ]
    resetForm();
};
const onConfirm = async () => {
    //  [{bankCode:BC,bankName:中国银行,productCode:3011},{bankCode:CBC,bankName:中国建设银行,productCode:3010},{bankCode:ABC,bankName:中国农业银行,productCode:3009},{bankCode:CMBC,bankName:中国招商银行,productCode:3008},{bankCode:ICBC,bankName:中国工商银行,productCode:1931}]
    await ruleFormRef.value?.validate(async (isOk) => {
        if (isOk) {
            const arr: any = {}

            channelForm.extInfo && channelForm.extInfo.forEach((item: any) => {
                if (item.key) {
                    arr[item.key] = item.value
                }
            })

            const newArr = Object.keys(arr).length == 0 ? "{}" : JSON.stringify(arr)
            // 删除一个数据
            if (channelForm.id) {
                delete channelForm.remainderQuota
            }
            const res = await voucherSaveOrUpdateSavePost({ ...channelForm, extInfo: newArr });
            if (res.code == 20000) {
                if(channelForm.id){
                    emit('searchEdit')
                }else{

                    emit("refresh");
                }
                onClose();
                ElMessage({
                    type: "success",
                    message: channelForm.id ? "权益券编辑成功" : "权益券新增成功",
                });
            }

        } else {
            ElMessage({
                type: "error",
                message: channelForm.id
                    ? "权益券编辑失败 请重试！"
                    : "权益券新增失败 请重试！",
            });
        }
    });
};
const btnAdd = () => {
    channelForm.extInfo.push({
        key: null,
        value: null,
    });
};
// 选择其他类型 
const equityVoucherTypeChange=(e:any)=>{
    console.log(e);
    if(e!=1){
        channelForm.reductionVoucherAmount=null
    }
    
}
const removeDomain = (item: any) => {
    const index = channelForm.extInfo.indexOf(item)
    if (index !== -1) {
        channelForm.extInfo.splice(index, 1)
    }
}
const resetForm = () => {
    ruleFormRef.value?.resetFields();
};

defineExpose({
    show,
    changeClick
});
</script>

<template>
    <SysDialog :title="dialogBasic.title" :width="dialogBasic.width" :height="dialogBasic.height"
        :show-footer="dialogBasic.showFooter" :visible="dialogBasic.visible" :margin-top="dialogBasic.marginTop"
        @on-close="onClose" @on-confirm="onConfirm">
        <template v-slot:content>
            <div class="channel-form">
                <el-form ref="ruleFormRef" :model="channelForm" :rules="rules" label-width="130px" class="demo-ruleForm"
                    status-icon>
                    <el-form-item label="供应商编码" prop="supplierCode">
                        <BlackSelect v-model:select-value="channelForm.supplierCode" :multiple="false"
                            :options="listCollect.supplierList"></BlackSelect>
                    </el-form-item>
                    <el-form-item label="供应商权益编码" prop="supplierEquityVoucherCode">
                        <!-- <el-input v-model="channelForm.supplierEquityVoucherCode" /> -->
                        <AddInput v-model:model-value="channelForm.supplierEquityVoucherCode" clearable></AddInput>

                    </el-form-item>
                    <el-form-item label="权益券名称" prop="equityVoucherName">
                        <!-- <el-input v-model="channelForm.equityVoucherName" /> -->
                         <AddInput v-model:model-value="channelForm.equityVoucherName" clearable></AddInput>
                    </el-form-item>
                    <!-- :disabled="channelForm.id?true:false" -->
                    <el-form-item label="权益券类型" prop="equityVoucherType">
                        <BlackSelect @my-change="equityVoucherTypeChange" v-model:select-value="channelForm.equityVoucherType" :multiple="false" 
                            :options="schemeConfigletailsType"></BlackSelect>
                    </el-form-item>


                  

                    <el-form-item label="立减金额度" prop="reductionVoucherAmount" v-if="channelForm.equityVoucherType==1">
                 
                        <el-input-number style="width: 100%;" v-model.number="channelForm.reductionVoucherAmount"
                            clearable placeholder="请输入立减金额度" :min="0" :precision="2" :controls="false"  />
                    </el-form-item>
                    <el-row style="width: 100%;">
                        <el-col :span="12">
                            <el-form-item label="领取类型" prop="receiveType">
                                <BlackSelect v-model:select-value="channelForm.receiveType" @my-change="changeClick" 
                                    style="width: 100%;" :multiple="false" :options="virtualType"></BlackSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">

                            <el-form-item label="领取值" prop="receiveValue" label-width="80">
                                <BlackSelect v-model:select-value="channelForm.receiveValue" :multiple="false" 
                                    :options="listCollect.virtualList"></BlackSelect>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="过期期限" prop="expiryPeriod">
                        <el-input v-model.number="channelForm.expiryPeriod" type="number" placeholder="过期期限">
                            <template #append>
                                <BlackSelect style="width: 100px;" v-model:select-value="channelForm.expiryPeriodType"
                                    disabled :options="expiryPeriodType"></BlackSelect>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="是否启用" prop="enabled">
                        <my-select v-model:select-value="channelForm.enabled" :multiple="false"
                            :options="isShow"></my-select>
                    </el-form-item>

                    <el-form-item v-for="(domain, index) in channelForm.extInfo" :key="index"
                        :label="'信息扩展' + (index + 1)">
                        <el-row style="width: 100%" justify="space-around">
                            <el-col :span="6">
                                <el-input v-model="domain.key" placeholder="请输入value"
                                    :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"></el-input>
                            </el-col>
                            <el-col :span="15">
                                <el-input v-model="domain.value" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                                    placeholder="请输入value" clearable></el-input>
                            </el-col>
                            <el-col :span="2">
                                <el-button type="danger" style="margin-top: 12px" size="small"
                                    @click="removeDomain(domain)" :icon="Minus" />
                            </el-col>
                        </el-row>
                    </el-form-item>

                    <el-form-item label="添加信息扩展">
                        <el-button type="primary" @click="btnAdd" :icon="Plus" style="width: 100%" />
                    </el-form-item>
                </el-form>
            </div>

        </template>
    </SysDialog>
</template>

<style lang='scss' scoped>
.channel-form {
    height: 600px;
    overflow: auto;
}
:deep(.el-input-number) .el-input__inner {
    text-align: left;
}
</style>
